<template>
  <div class="app-container">
    <el-row :gutter="10">
      <!--树结构-->
      <el-col :span="4" :xs="24">
        <div class="app-container-tree-border">
          <el-input v-model="syTypeName" placeholder="请输入试验类别" clearable size="small" prefix-icon="el-icon-search" />
          <el-tree :data="options" :props="defaultProps" :expand-on-click-node="false" :filter-node-method="filterNode" ref="tree" node-key="id" default-expand-all highlight-current @node-click="handleNodeClick">
            <div slot-scope="{node, data}" class="custom-tree-node" :title="node.label" v-text="node.label"></div>
          </el-tree>
        </div>
      </el-col>

      <!--      右侧展示该试验的配置信息-->
      <el-col :span="20" :xs="24">
        <div class="app-container-table-border">
          <div v-if="oneShow">
            <el-divider content-position="center">编号规则配置</el-divider>
            <el-row>
              <el-form :inline="true" ref="form" :model="form" :rules="rules" label-width="120px" :loading="loading">
                <el-form-item label="编号规则名称" prop="ruleName">{{ form.ruleName }}</el-form-item>
                <el-form-item label="分隔符字典" prop="fgf">
                  <el-select clearable v-model="form.fgf" placeholder="请选择分隔符字典" @change="fgfChange(form.fgf)">
                    <el-option v-for="dict in dict.type.fgf" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                  </el-select>
                </el-form-item>
                <div style="float: right;">
                  <el-button size="mini" :loading="buttonLoading" type="primary" @click="submitForm">
                    保
                    存
                  </el-button>
                </div>
                <el-table border stripe :data="form.tableData">
                  <el-table-column label="序号" align="center" width="80">
                    <template #default="scope">
                      <span>{{ scope.$index + 1 }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="pType" label="规则类型" align="center" :show-overflow-tooltip="true">
                    <template #header>
                      <el-tooltip class="item" effect="dark" :content="'这是必填项'" placement="top">
                        <span>
                          <span style="color: red;">*</span>
                          规则类型
                        </span>
                      </el-tooltip>
                    </template>
                    <template #default="scope">
                      <el-form-item :prop="'tableData[' + scope.$index + '].pType'" :rules="rules.pType">
                        <el-select @change="pTypeChange(scope.row)" clearable v-model="scope.row.pType" placeholder="请选择规则类型">
                          <el-option v-for="dict in dict.type.sycs_rule_p" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                        </el-select>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column prop="sl" label="示例" align="center" :show-overflow-tooltip="true" />
                  <el-table-column prop="pContent" label="规则内容" align="center" :show-overflow-tooltip="true">
                    <template #header>
                      <el-tooltip class="item" effect="dark" :content="'这是必填项'" placement="top">
                        <span>
                          <span style="color: red;">*</span>
                          规则内容
                        </span>
                      </el-tooltip>
                    </template>
                    <template #default="scope">
                      <el-form-item :prop="'tableData[' + scope.$index + '].pContent'" :rules="rules.pContent">
                        <el-input clearable v-model="scope.row.pContent" size="small" placeholder="请输入内容" @blur="createRes(scope.row)" v-if="scope.row.pType != '33'"></el-input>
                        <el-input clearable v-model="scope.row.pContent" size="small" placeholder="请输入内容" @blur="createRes(scope.row)" :disabled="true" v-else></el-input>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" align="center" fixed="right">
                    <template #default="scope">
                      <el-popconfirm title="确定删除该条数据吗？" @confirm="dataDel(scope.row, scope.$index)">
                        <el-link slot="reference" type="primary" style="margin-right: 20px;">删除</el-link>
                      </el-popconfirm>
                      <el-link type="primary" @click="dataAdd(scope.row)" style="margin-right: 20px;" :disabled="form.tableData.length > 5">添加</el-link>
                      <el-link type="primary" @click="moveupOrmovedown(scope.row, scope.$index, 'up')" style="margin-right: 20px;" :disabled="!(scope.$index != 0)">上移</el-link>
                      <el-link type="primary" @click="moveupOrmovedown(scope.row, scope.$index, 'down')" :disabled="scope.$index == (form.tableData.length - 1)">下移</el-link>
                    </template>
                  </el-table-column>
                </el-table>
              </el-form>
            </el-row>
            <el-divider content-position="center">示例信息</el-divider>
            <el-row>
              <el-table border stripe :data="slList">
                <el-table-column label="编号规则名称" align="center" prop="bhName" :show-overflow-tooltip="true" />
                <el-table-column label="效果预览" align="center" prop="bhValue" :show-overflow-tooltip="true" />
              </el-table>
            </el-row>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { listBsRule, getBsRule, delBsRule, addBsRule, updateBsRule, getRule } from "@/api/sycs/bsRule";
import { syTpyeTreeBig } from "@/api/base/syType";
import { mapGetters } from "vuex";

export default {
  name: "BsRule",
  dicts: ["sycs_rule_p", "fgf"],
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 编号规则设置表格数据
      bsRuleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deptId: undefined,
        syTypeId: undefined,
        ruleName: undefined,
        fgf: undefined,
        p1Type: undefined,
        p1Content: undefined,
        p2Type: undefined,
        p2Content: undefined,
        p3Type: undefined,
        p3Content: undefined,
        p4Type: undefined,
        p4Content: undefined,
        p5Type: undefined,
        p5Content: undefined,
        p6Type: undefined,
        p6Content: undefined
      },
      // 表单参数
      form: {
        ruleName: "样品编号 / 记录编号 / 报告编号",
        tableData: [
          {
            date: Date.now(),
            sl: "",
            pType: undefined,
            pContent: undefined
          }
        ]
      },
      // 表单校验
      rules: {
        fgf: [{ required: true, message: "分隔符字典不能为空", trigger: "change" }],
        pType: [{ required: true, message: "规则类型不能为空", trigger: "change" }],
        pContent: [{ required: true, message: "规则内容不能为空", trigger: "blur" }]
      },
      syTypeName: undefined,
      options: [],
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 当前树节点
      currentNode: {},
      oneShow: false, // 点击树显示子表
      slList: [
        {
          bhName: "样品编号",
          bhValue: undefined
        },
        {
          bhName: "记录编号",
          bhValue: undefined
        },
        {
          bhName: "报告编号",
          bhValue: undefined
        }
      ],
      res: undefined // 示例值
    };
  },
  created() {
    this.getDeptTree();
  },
  computed: {
    ...mapGetters(["deptId"])
  },
  watch: {
    deptId(newValue, oldValue) {
      this.deptId = newValue;
      console.log("-----------deptId-----------", this.deptId);
    }
  },
  methods: {
    /** 查询编号规则设置列表 */
    getList() {
      this.oneShow = true;
      this.loading = true;
      listBsRule(this.queryParams).then((response) => {
        this.bsRuleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询树结构 */
    getDeptTree() {
      syTpyeTreeBig().then((response) => {
        this.options = response.data;
      });
    },
    // 根据试验类型id查询编号规则
    getRule() {
      if (!this.deptId) {
        this.$alert("", "请选择试验室", {
          confirmButtonText: "确定",
          type: "warning",
          center: true
        });
        return;
      }
      this.oneShow = true;
      this.loading = true;
      const params = {
        syTypeId: this.currentNode.id,
        deptId: this.deptId
      };
      getRule(params).then((response) => {
        if (!!response && !!response.data) {
          this.form = response.data;
          const data = response.data;
          const tableData = [];
          if (!!data.p1Type && !!data.p1Content && !data.p2Type && !data.p2Content) {
            const obj = {
              date: Date.now(),
              sl: "",
              pType: data.p1Type,
              pContent: data.p1Content
            };
            this.$set(obj, "sl", this.createSl(obj.pType));
            tableData.push(obj);
          } else if (!!data.p1Type && !!data.p1Content && !!data.p2Type && !!data.p2Content && !data.p3Type && !data.p3Content) {
            const obj = {
              date: Date.now(),
              sl: "",
              pType: data.p1Type,
              pContent: data.p1Content
            };
            this.$set(obj, "sl", this.createSl(obj.pType));
            const obj2 = {
              date: Date.now(),
              sl: "",
              pType: data.p2Type,
              pContent: data.p2Content
            };
            this.$set(obj2, "sl", this.createSl(obj2.pType));
            tableData.push(obj);
            tableData.push(obj2);
          } else if (!!data.p1Type && !!data.p1Content && !!data.p2Type && !!data.p2Content && !!data.p3Type && !!data.p3Content && !data.p4Type && !data.p4Content) {
            const obj = {
              date: Date.now(),
              sl: "",
              pType: data.p1Type,
              pContent: data.p1Content
            };
            this.$set(obj, "sl", this.createSl(obj.pType));
            const obj2 = {
              date: Date.now(),
              sl: "",
              pType: data.p2Type,
              pContent: data.p2Content
            };
            this.$set(obj2, "sl", this.createSl(obj2.pType));
            const obj3 = {
              date: Date.now(),
              sl: "",
              pType: data.p3Type,
              pContent: data.p3Content
            };
            this.$set(obj3, "sl", this.createSl(obj3.pType));
            tableData.push(obj);
            tableData.push(obj2);
            tableData.push(obj3);
          } else if (
            !!data.p1Type &&
            !!data.p1Content &&
            !!data.p2Type &&
            !!data.p2Content &&
            !!data.p3Type &&
            !!data.p3Content &&
            !!data.p4Type &&
            !!data.p4Content &&
            !data.p5Type &&
            !data.p5Content
          ) {
            const obj = {
              date: Date.now(),
              sl: "",
              pType: data.p1Type,
              pContent: data.p1Content
            };
            this.$set(obj, "sl", this.createSl(obj.pType));
            const obj2 = {
              date: Date.now(),
              sl: "",
              pType: data.p2Type,
              pContent: data.p2Content
            };
            this.$set(obj2, "sl", this.createSl(obj2.pType));
            const obj3 = {
              date: Date.now(),
              sl: "",
              pType: data.p3Type,
              pContent: data.p3Content
            };
            this.$set(obj3, "sl", this.createSl(obj3.pType));
            const obj4 = {
              date: Date.now(),
              sl: "",
              pType: data.p4Type,
              pContent: data.p4Content
            };
            this.$set(obj4, "sl", this.createSl(obj4.pType));
            tableData.push(obj);
            tableData.push(obj2);
            tableData.push(obj3);
            tableData.push(obj4);
          } else if (
            !!data.p1Type &&
            !!data.p1Content &&
            !!data.p2Type &&
            !!data.p2Content &&
            !!data.p3Type &&
            !!data.p3Content &&
            !!data.p4Type &&
            !!data.p4Content &&
            !!data.p5Type &&
            !!data.p5Content &&
            !data.p6Type &&
            !data.p6Content
          ) {
            const obj = {
              date: Date.now(),
              sl: "",
              pType: data.p1Type,
              pContent: data.p1Content
            };
            this.$set(obj, "sl", this.createSl(obj.pType));
            const obj2 = {
              date: Date.now(),
              sl: "",
              pType: data.p2Type,
              pContent: data.p2Content
            };
            this.$set(obj2, "sl", this.createSl(obj2.pType));
            const obj3 = {
              date: Date.now(),
              sl: "",
              pType: data.p3Type,
              pContent: data.p3Content
            };
            this.$set(obj3, "sl", this.createSl(obj3.pType));
            const obj4 = {
              date: Date.now(),
              sl: "",
              pType: data.p4Type,
              pContent: data.p4Content
            };
            this.$set(obj4, "sl", this.createSl(obj4.pType));
            const obj5 = {
              date: Date.now(),
              sl: "",
              pType: data.p5Type,
              pContent: data.p5Content
            };
            this.$set(obj5, "sl", this.createSl(obj5.pType));
            tableData.push(obj);
            tableData.push(obj2);
            tableData.push(obj3);
            tableData.push(obj4);
            tableData.push(obj5);
          } else if (
            !!data.p1Type &&
            !!data.p1Content &&
            !!data.p2Type &&
            !!data.p2Content &&
            !!data.p3Type &&
            !!data.p3Content &&
            !!data.p4Type &&
            !!data.p4Content &&
            !!data.p5Type &&
            !!data.p5Content &&
            !!data.p6Type &&
            !!data.p6Content
          ) {
            const obj = {
              date: Date.now(),
              sl: "",
              pType: data.p1Type,
              pContent: data.p1Content
            };
            this.$set(obj, "sl", this.createSl(obj.pType));
            const obj2 = {
              date: Date.now(),
              sl: "",
              pType: data.p2Type,
              pContent: data.p2Content
            };
            this.$set(obj2, "sl", this.createSl(obj2.pType));
            const obj3 = {
              date: Date.now(),
              sl: "",
              pType: data.p3Type,
              pContent: data.p3Content
            };
            this.$set(obj3, "sl", this.createSl(obj3.pType));
            const obj4 = {
              date: Date.now(),
              sl: "",
              pType: data.p4Type,
              pContent: data.p4Content
            };
            this.$set(obj4, "sl", this.createSl(obj4.pType));
            const obj5 = {
              date: Date.now(),
              sl: "",
              pType: data.p5Type,
              pContent: data.p5Content
            };
            this.$set(obj5, "sl", this.createSl(obj5.pType));
            const obj6 = {
              date: Date.now(),
              sl: "",
              pType: data.p6Type,
              pContent: data.p6Content
            };
            this.$set(obj6, "sl", this.createSl(obj6.pType));
            tableData.push(obj);
            tableData.push(obj2);
            tableData.push(obj3);
            tableData.push(obj4);
            tableData.push(obj5);
            tableData.push(obj6);
          }
          this.$set(this.form, "tableData", tableData);
          this.$nextTick(() => {
            this.$refs.form.clearValidate();
          });
          this.createRes();
        } else {
          this.form = {
            ruleName: "样品编号 / 记录编号 / 报告编号",
            tableData: [
              {
                date: Date.now(),
                sl: "",
                pType: undefined,
                pContent: undefined
              }
            ]
          };
          this.slList = [
            {
              bhName: "样品编号",
              bhValue: undefined
            },
            {
              bhName: "记录编号",
              bhValue: undefined
            },
            {
              bhName: "报告编号",
              bhValue: undefined
            }
          ];
          this.$nextTick(() => {
            this.$refs.form.clearValidate();
          });
        }
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        ruleId: undefined,
        deptId: undefined,
        syTypeId: undefined,
        ruleName: undefined,
        fgf: undefined,
        p1Type: undefined,
        p1Content: undefined,
        p2Type: undefined,
        p2Content: undefined,
        p3Type: undefined,
        p3Content: undefined,
        p4Type: undefined,
        p4Content: undefined,
        p5Type: undefined,
        p5Content: undefined,
        p6Type: undefined,
        p6Content: undefined,
        delFlag: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加编号规则设置";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      let ruleId = row.ruleId || this.ids;
      getBsRule(ruleId).then((response) => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改编号规则设置";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (!this.currentNode.id) {
            this.$message({ message: "请选择试验类型", type: "warning" });
            return;
          }
          // 拼接参数
          // let deptId= this.deptId?this.deptId:this.$store.state.dept.deptId;
          if (!this.deptId) {
            this.$alert("", "请选择试验室", {
              confirmButtonText: "确定",
              type: "warning",
              center: true
            });
            return;
          }
          this.$set(this.form, "deptId", this.deptId);
          this.$set(this.form, "syTypeId", this.currentNode.id);
          for (let i = 0; i < this.form.tableData.length; i++) {
            this.$set(this.form, "p" + (i + 1) + "Type", this.form.tableData[i].pType);
            this.$set(this.form, "p" + (i + 1) + "Content", this.form.tableData[i].pContent);
          }
          this.buttonLoading = true;
          if (this.form.ruleId != null) {
            updateBsRule(this.form)
              .then((response) => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          } else {
            addBsRule(this.form)
              .then((response) => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      let ruleIds = row.ruleId || this.ids;
      this.$modal
        .confirm('是否确认删除编号规则设置编号为"' + ruleIds + '"的数据项？')
        .then(() => {
          this.loading = true;
          return delBsRule(ruleIds);
        })
        .then(() => {
          this.loading = false;
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {})
        .finally(() => {
          this.loading = false;
        });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.$set(this.currentNode, "id", data.id);
      this.$set(this.currentNode, "label", data.label);
      if (!!data.children) {
        this.oneShow = false;
      } else {
        this.getRule();
      }
    },
    // 删除一行
    dataDel(row, index) {
      if (!!this.form.tableData && this.form.tableData.length > 1) {
        // let i = this.form.tableData.findIndex(item => {
        //   if (item.date == row.date) {
        //     return true
        //   }
        // })
        // for (let i=0; i<this.form.tableData.length; i++) {
        //   if (this.form.tableData[i].date == row.date) {
        //     index = i;
        //     break;
        //   }
        // }
        this.form.tableData.splice(index, 1);
      } else {
        this.$message({
          message: "无法删除当前行",
          type: "error",
          offset: 150
        });
      }
      this.createRes(row);
    },
    // 添加一行
    dataAdd(row) {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          let obj = {
            date: Date.now(),
            pType: undefined,
            pContent: undefined
          };
          this.form.tableData.push(obj);
          this.createRes(row);
        } else {
          return false;
        }
      });
    },
    moveupOrmovedown(row, index, type) {
      let arr = this.form.tableData;
      let findIndex = this.form.tableData.findIndex((item) => item.date === row.date);
      index = findIndex > this.queryParams.pageSize - 1 ? findIndex : index;
      type === "up" ? arr.splice(index - 1, 1, ...arr.splice(index, 1, arr[index - 1])) : arr.splice(index, 1, ...arr.splice(index + 1, 1, arr[index]));
      this.createRes(row);
    },
    // 改变下拉选择框的值时,判断后将值添加到示例中
    pTypeChange(row) {
      let pType = row.pType;
      let sl;
      switch (pType) {
        case "00":
          sl = "TG";
          if (!!row.pContent) {
            row.pContent = undefined;
          }
          break;
        case "0100":
          sl = new Date().getFullYear();
          break;
        case "0101":
          sl = new Date().getFullYear() + "" + (new Date().getMonth() + 1 > 10 ? new Date().getMonth() + 1 : "0" + (new Date().getMonth() + 1));
          break;
        case "0102":
          sl = (new Date().getMonth() + 1 > 10 ? new Date().getMonth() + 1 : "0" + (new Date().getMonth() + 1)) + "" + new Date().getFullYear();
          break;
        case "0200":
          sl = "0001";
          break;
        case "0201":
          sl = "001";
          break;
        case "33":
          sl = "YP/JL/BG";
          row.pContent = "YP/JL/BG";
          break;
        default:
          sl = undefined;
      }
      let i = this.form.tableData.findIndex((item) => {
        if (item.date === row.date) {
          return true;
        }
      });
      this.$set(this.form.tableData[i], "sl", sl);
      this.createRes(row);
    },
    createSl(pType) {
      let sl;
      switch (pType) {
        case "00":
          sl = "TG";
          break;
        case "0100":
          sl = new Date().getFullYear();
          break;
        case "0101":
          sl = new Date().getFullYear() + "" + (new Date().getMonth() + 1 > 10 ? new Date().getMonth() + 1 : "0" + (new Date().getMonth() + 1));
          break;
        case "0102":
          sl = (new Date().getMonth() + 1 > 10 ? new Date().getMonth() + 1 : "0" + (new Date().getMonth() + 1)) + "" + new Date().getFullYear();
          break;
        case "0200":
          sl = "0001";
          break;
        case "0201":
          sl = "001";
          break;
        case "33":
          sl = "YP/JL/BG";
          break;
        default:
          sl = undefined;
      }
      return sl;
    },
    createRes(row) {
      let fgfLabel = "";
      // 获取分隔符
      for (let i = 0; i < this.dict.type.fgf.length; i++) {
        const dict = this.dict.type.fgf[i];
        if (dict.value == this.form.fgf) {
          fgfLabel = dict.label;
          break;
        } else {
          fgfLabel = "";
        }
      }
      this.res = "";
      for (let i = 0; i < this.form.tableData.length; i++) {
        if (i < this.form.tableData.length - 1) {
          if (!!this.form.tableData[i].pContent) {
            this.res += this.form.tableData[i].pContent + fgfLabel;
          }
        } else {
          if (!!this.form.tableData[i].pContent) {
            this.res += this.form.tableData[i].pContent;
          }
        }
      }
      this.slList[0].bhValue = this.res.replace("YP/JL/BG", "YP");
      this.slList[1].bhValue = this.res.replace("YP/JL/BG", "JL");
      this.slList[2].bhValue = this.res.replace("YP/JL/BG", "BG");
    },
    fgfChange(fgf) {
      this.createRes();
    }
  }
};
</script>
<style lang="scss" scoped>
  @import "~@/assets/styles/demo.scss";

  .el-form-item {
    margin-bottom: 0 !important;
  }
</style>
